package at.horario.web.pages;

import at.horario.model.Horario;
import at.horario.model.HorarioSchedule;
import at.horario.service.HorarioScheduleManager;
import static org.apache.commons.lang.time.DateUtils.addHours;
import static org.apache.commons.lang.time.DateUtils.addMinutes;
import org.apache.wicket.Page;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.yui.calendar.DateTimeField;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.ComponentFeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.collections.MicroMap;
import static org.apache.wicket.util.string.interpolator.MapVariableInterpolator.interpolate;
import org.apache.wicket.validation.validator.DateValidator;
import org.quartz.SchedulerException;

import java.util.Arrays;
import java.util.Date;

@AuthorizeInstantiation({"user", "admin"})
public class HorarioScheduleForm extends PageTemplate {
    @SpringBean(name = "horarioScheduleManager")
    private HorarioScheduleManager horarioScheduleManager;

    private final Page backPage;

    /**
     * Constructor user to create a new user
     *
     * @param backPage page to navigate to after this page completes its work
     */


    /**
     * Constructor used to edit an model
     *
     * @param backPage page to navigate to after this page completes its work
     * @param model    model to edit
     */
    public HorarioScheduleForm(final Page backPage, IModel model) {
        this.backPage = backPage;

        // Create and add the form
        EditForm form = new EditForm("horarioschedule-form", model) {
            protected void onSave(HorarioSchedule hs) {
                onSaveHorarioSchedule(hs);
            }

            protected void onCancel() {
                onCancelEditing();
            }

            protected void onDelete(HorarioSchedule user) {
                onDeleteUser(user);
            }
        };
        add(form);
    }

    public HorarioScheduleForm(Page page, Horario horario) {
        this(page, new Model(new HorarioSchedule(horario)));
    }


    /**
     * Listener method for save action
     *
     * @param horarioSchedule horarioSchedule bean
     */
    void onSaveHorarioSchedule(HorarioSchedule horarioSchedule) {
    try {
        HorarioSchedule irmao = horarioScheduleManager.irmao(horarioSchedule);
        if (irmao != null){
            String message = interpolate(getLocalizer().getString("horarioschedule.irmao.existe", this),
                    new MicroMap("name", irmao));
            getSession().info(message);

        }   else{
            horarioScheduleManager.saveSchedule(horarioSchedule);
            String message = interpolate(getLocalizer().getString("horarioschedule.saved", this),
                    new MicroMap("name", horarioSchedule.getId()));
            getSession().info(message);
            setRedirect(true);
            setResponsePage(backPage);
        }
        } catch (SchedulerException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    /**
     * Listener method for delete action
     *
     * @param user user bean
     */
    void onDeleteUser(HorarioSchedule user) {
//        userManager.remove(user.getId());
//
//        String message = MapVariableInterpolator.interpolate(getLocalizer().getString("user.deleted", this),
//                new MicroMap("name", user.getFullName()));
//        getSession().info(message);
//
//        backPage.get("feedback").setVisible(true);
//        setRedirect(true);
//        setResponsePage(backPage);
    }

    /**
     * Lister method for cancel action
     */
    private void onCancelEditing() {
        setResponsePage(backPage);
    }


    private abstract class EditForm extends BaseForm {
        String em;


        /**
         * Convenience method that adds and prepares a form component
         *
         * @param fc    form component
         * @param label IModel containing the string used in ${label} variable of
         *              validation messages
         */
        protected void add(FormComponent fc, IModel label) {
            // Add the component to the form
            super.add(fc);
            // Set its label model
            fc.setLabel(label);
            // Add feedback panel that will be used to display component errors
            add(new ComponentFeedbackPanel(fc.getId() + "-feedback", fc));
        }

        /**
         * Constructor
         *
         * @param id      component id
         * @param horario User object that will be used as a form bean
         */
        public EditForm(String id, final IModel model) {
            /*
             * We wrap the horario bean with a CompoundPropertyModel, this allows
             * us to easily connect form components to the bean properties
             * (component id is used as the property expression)
             */

            super(id, model);
            final HorarioSchedule hs = (HorarioSchedule) model.getObject();

            TextField horarioTextField = new TextField("horario", new PropertyModel(model, "horario"));
            horarioTextField.setRequired(true);
            horarioTextField.setEnabled(false);
            final DropDownChoice emCombo = new DropDownChoice("em", new PropertyModel(this, "em"), Arrays.asList("Imediatamente", "1 minuto", "5 minutos", "15 minutos", "1 hora"));
            emCombo.setRequired(true);

//            final DateTextField dateTextField = DateTextField.forDatePattern("processar", new PropertyModel(model, "processar"), "yyyy-MM-dd hh:mm:ss");
//            final DatePicker picker = new DatePicker();
//            dateTextField.add(picker);
//            dateTextField.setEnabled(true);
//            dateTextField.setRequired(true);
//            dateTextField.add(DateValidator.minimum(new Date()));
            final DateTimeField dateTextField = new DateTimeField("processar", new PropertyModel(model, "processar"));
            dateTextField.add(DateValidator.minimum(new Date()));
            dateTextField.setOutputMarkupId(true);


            TextField emailAlertaTextField = new TextField("emailAlerta", new PropertyModel(model, "emailAlerta"));

            add(horarioTextField, new ResourceModel("horarioschedule.horario"));
            add(emCombo, new ResourceModel("horarioschedule.em"));
            add(dateTextField, new ResourceModel("horarioschedule.processar"));
            add(emailAlertaTextField, new ResourceModel("horarioschedule.emailAlerta"));

            emCombo.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                protected void onUpdate(AjaxRequestTarget target) {
                    String valor = (String) emCombo.getModelObject();
                    Date d = new Date();
                    if (valor.equalsIgnoreCase("1 minuto"))
                        d = addMinutes(d, 1);
                    else if (valor.equalsIgnoreCase("5 minuto"))
                        d = addMinutes(d, 5);
                    else if (valor.equalsIgnoreCase("15 minutos"))
                        d = addMinutes(d, 15);
                    else if (valor.equalsIgnoreCase("1 hora"))
                        d = addHours(d, 1);

                    HorarioSchedule hs = (HorarioSchedule) model.getObject();
                    hs.setProcessar(d);
                    dateTextField.setEnabled(valor.equalsIgnoreCase("Custom"));
                    target.addComponent(dateTextField);
                }
            });


            add(new Button("save", new Model("Save")) {
                public void onSubmit() {
                    onSave(hs);
                }
            });

            Button delete = new Button("delete", new Model("Delete")) {
                public void onSubmit() {
                    //onDelete((Horario) getForm().getModelObject());
                }
            };

//            if (horario.getId() == null) {
//                delete.setVisible(false);
//                delete.setEnabled(false);
//            }
            add(delete);

            /*
             * Notice the setDefaultFormProcessing(false) call at the end. This
             * tells wicket that when this button is pressed it should not
             * perform any form processing (ie bind request values to the bean).
             */
            add(new Button("cancel", new Model("Cancel")) {
                public void onSubmit() {
                    onCancel();
                }
            }.setDefaultFormProcessing(false));

        }

        /**
         * Callback for cancel button
         */
        protected abstract void onCancel();

        /**
         * Callback for delete button
         *
         * @param hs hs bean
         */
        protected abstract void onDelete(HorarioSchedule hs);

        /**
         * Callback for save button
         *
         * @param hs hs bean
         */
        protected abstract void onSave(HorarioSchedule hs);
    }


}